//
//  ChatInputToolBar.swift
//  IMUIDemo
//
//  Created by tbbMacmini on 2025/3/21.
//

import UIKit
import Photos
class ChatInputToolBar: UIView {
    
    var textInputBlock:((String) -> ())?
    var imageInputBlock:((UIImage) -> ())?
    
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.returnKeyType = .send;
        textField.enablesReturnKeyAutomatically = true
        textField.delegate = self
        textField.borderStyle = .roundedRect
        return textField
    }()
    
    lazy var imageBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("图片", for: .normal)
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.addTarget(self, action: #selector(selectedImage(_:)), for: .touchUpInside)
        return btn;
    }()
    
    lazy var sendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.addTarget(self, action: #selector(sendText(_:)), for: .touchUpInside)
        return btn;
    }()
    
    
    private let picker = UIImagePickerController()

    override init(frame: CGRect) {
        super.init(frame: frame);
        setupView();
        configurePicker();
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //Picker Configuration
    private func configurePicker() {
        picker.delegate = self
        picker.sourceType = .photoLibrary
        picker.mediaTypes = ["public.image"]
        picker.allowsEditing = false // 允许编辑
    }
    
    private func setupView() {
        self.backgroundColor = UIColor.lightGray;
        
        self.addSubview(imageBtn);
        imageBtn.snp.makeConstraints { make in
            make.right.equalTo(-10);
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 50, height: 40))
        }
        
        self.addSubview(sendBtn);
        sendBtn.snp.makeConstraints { make in
            make.right.equalTo(imageBtn.snp.left).offset(-10)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 50, height: 40))
        }
        
        
        self.addSubview(textField);
        textField.snp.makeConstraints { make in
            make.left.equalTo(10);
            make.right.equalTo(sendBtn.snp.left).offset(-10)
            make.height.equalTo(40)
            make.centerY.equalToSuperview()
        }
    }

    
    @objc func sendText(_ sender:UIButton) {
        if let text = textField.text {
            textField.text = ""
            textInputBlock?(text)
        }
    }
    
    @objc func selectedImage(_ sender:UIButton) {
        textField.resignFirstResponder();
        
        // 检查权限
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            DispatchQueue.main.async {
                switch status {
                case .authorized, .limited:
                    if let self = self {
                        self.parentViewController?.present(self.picker, animated: true)
                    }
                default:
                    print("没有权限")
                }
            }
        }
    }
    
    
    
    
    
}

extension ChatInputToolBar:UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let text = textField.text {
            textField.text = "";
            textInputBlock?(text);
        }
        return true;
    }
}



//UIImagePickerControllerDelegate
extension ChatInputToolBar: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        
        if let originalImage = info[.originalImage] as? UIImage {
            imageInputBlock?(originalImage);
        }
        
    }
        
}

extension UIView {
    /// 获取当前视图所在的 UIViewController
    var parentViewController: UIViewController? {
        var responder: UIResponder? = self
        while let current = responder {
            if let viewController = current as? UIViewController {
                return viewController
            }
            responder = current.next
        }
        return nil
    }
}
